#include "key_rgb_relay.h"

Key_RGB_Relay::Key_RGB_Relay(Serial_Tx_Thread *tx_thread , Serial_Rx_Thread *rx_thread)
{
    this->tx_thread = tx_thread;
    this->rx_thread = rx_thread;

    connect(this,SIGNAL(signal_write_sp_tx_queue(char*,unsigned int)),this->tx_thread,SLOT(slot_write_serial_port_tx_queue(char*, unsigned int)));

    rgb_relay.dev_type = (unsigned short)qToLittleEndian((unsigned short)TERMINAL_DEV_TYPE);
    //rgb_relay.dev_type = TERMINAL_DEV_TYPE;

    //qDebug() << "dev_type = " << rgb_relay.dev_type;
}


Key_RGB_Relay::~Key_RGB_Relay()
{

}


void Key_RGB_Relay::set_r_brightness(unsigned short dev_id,unsigned short value)
{
    qDebug() << ">>> set_r_brightness >>>" << value;

    rgb_relay.r_pwm_duty = value;

    if(dev_id != 0xFFFF)send_rgb_data_to_device(dev_id);
}

void Key_RGB_Relay::set_g_brightness(unsigned short dev_id,unsigned short value)
{
    qDebug() << ">>> set_g_brightness >>>" << value;

    rgb_relay.g_pwm_duty = value;

    if(dev_id != 0xFFFF)send_rgb_data_to_device(dev_id);
}

void Key_RGB_Relay::set_b_brightness(unsigned short dev_id,unsigned short value)
{
    qDebug() << ">>> set_b_brightness >>>" << value;

    rgb_relay.b_pwm_duty = value;

    if(dev_id != 0xFFFF)send_rgb_data_to_device(dev_id);
}

void Key_RGB_Relay::set_relay_onoff(unsigned short dev_id,bool onoff)
{
    //qDebug() << ">>> set_relay_onoff >>>" << onoff;

    if(onoff)rgb_relay.relay_onoff = 0x0001;
    else rgb_relay.relay_onoff = 0x0000;

    if(dev_id != 0xFFFF)send_rgb_data_to_device(dev_id);
}

void Key_RGB_Relay::send_rgb_data_to_device(unsigned short dev_id)
{
    unsigned char data_buff[14];

    unsigned int data_len = 0;
    TYP_UN_COMMUNICATE_BUFF p_data_send;
    My_Protocol my_protocol;

    //注意大小端模式
    data_buff[0] = (unsigned char)(dev_id >> 8);
    data_buff[1] = (unsigned char)dev_id;
    data_buff[2] = 0x1F;    //本地处理
    data_buff[3] = 0x03;    //设备控制
    data_buff[4] = (unsigned char)(rgb_relay.dev_type >> 8);
    data_buff[5] = (unsigned char)(rgb_relay.dev_type);
    data_buff[6] = (unsigned char)(rgb_relay.relay_onoff >> 8);
    data_buff[7] = (unsigned char)(rgb_relay.relay_onoff);
    data_buff[8] = (unsigned char)(rgb_relay.r_pwm_duty >> 8);
    data_buff[9] = (unsigned char)(rgb_relay.r_pwm_duty);
    data_buff[10] = (unsigned char)(rgb_relay.g_pwm_duty >> 8);
    data_buff[11] = (unsigned char)(rgb_relay.g_pwm_duty);
    data_buff[12] = (unsigned char)(rgb_relay.b_pwm_duty >> 8);
    data_buff[13] = (unsigned char)(rgb_relay.b_pwm_duty);

    data_len = my_protocol.protocol_data_package(CMD_MASTER_CTRL_SLAVE,sizeof(data_buff),(unsigned char*)&data_buff,&p_data_send);

    emit signal_write_sp_tx_queue((char*)&p_data_send.databuff,data_len);
}
